package com.tanhua.server.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.UserVoice;
import com.tanhua.domain.vo.AcceptVo;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.UserVoiceApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


/**
 * @author xie
 * @date 2021/8/22
 */
@Service
public class AcceptService {


    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private UserVoiceApi userVoiceApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    /**
     * 接语音
     * 有修改，把判断redis放在上面，如果3次不用先去查数据库，减少操作
     * @return
     */
    public AcceptVo acceptVoice() {
        //redis中查询到的次数转换成Integer临时存储点
        int queryValue=3;//默认3次
        String key="ACCEPT_NUM_"+ UserHolder.getUserId();
        String redisValue = redisTemplate.opsForValue().get(key);
        //有查询到redis的值就修改
        if(StringUtils.isNotEmpty(redisValue)){
            queryValue = Integer.parseInt(redisValue);
        }
        //判断当前次数是否大于0
        if(queryValue>0){
            --queryValue;
            redisTemplate.opsForValue().set(key,queryValue+"");
            //rocketMQTemplate.convertAndSend("tanhua",key);
        }
        else{
            throw new TanHuaException("免费接受语音次数已用完");
        }
        //获取当前用户的id
        Long currentUserId = UserHolder.getUserId();
        //根据当前用户查询UserInfo表 查询当前用户性别
        UserInfo currentUserInfo = userInfoApi.queryUserInfo(currentUserId);
        String currentUserInfoGender = currentUserInfo.getGender();
        AcceptVo acceptVo = new AcceptVo();
        //调用acceptVoice方法 传入性别参数 返回一个查询到对象
        UserVoice userVoice = userVoiceApi.acceptVoice(currentUserId,currentUserInfoGender);
        String voiceUrl = userVoice.getVoiceUrl();//语音文件地址
        Long userId = userVoice.getUserId();//上传用户id

        //根据上传用户id查询查询用户信息
        UserInfo userInfo = userInfoApi.queryUserInfo(userId);
        acceptVo.setId(userId.intValue());//上传用户id
        acceptVo.setSoundUrl(voiceUrl);
        BeanUtils.copyProperties(userInfo,acceptVo);//头像,昵称,年龄,性别
        acceptVo.setRemainingTimes(queryValue);
        return acceptVo;
    }
}
